#ifndef VPDCHECKMESSAGE_H
#define VPDCHECKMESSAGE_H
#include <stdint.h>
#include <string.h>
typedef struct MSG_ST_BUFFER
{
    char    buffer[1*1024*1024];
    int     len;
}msgStBuffer;
typedef struct VPD_CHECK_MSG
{
    uint32_t         cmdType;
    int              start;
    uint32_t         end;
    uint32_t         len;
    uint8_t          flag;
    uint8_t          isFully;
}vpdCheckMsg;
static inline void checkVpdMessage(char *buf,uint32_t len,vpdCheckMsg *msg,uint32_t MSG_HEAD,uint32_t MSG_LENS)
{
    msg->start=-1;
    msg->flag=0;
    msg->isFully=0;
    msg->len=0;
 //   printf("%s %1x %1x %1x %1x \n",__func__,buf[0],buf[1],buf[2],buf[3]);
    for(uint32_t i=0;i<len;i++)      //閬嶅巻鏁版嵁
    {
        uint32_t    *val_u32=(uint32_t *)buf+i;

        if(*val_u32==MSG_HEAD)      //check The msgHead
        {
            msg->start=i;
            msg->flag=1;
            msg->cmdType=MSG_HEAD;
            break;
        }
    }
    if(msg->start==-1) return;
    msg->end=len;           //set len to the end
    if(len-msg->start>=MSG_LENS)
    {
        msg->isFully=1;
        msg->end=msg->start+MSG_LENS;
    }
    msg->len=msg->end-msg->start;
    return ;
}
static inline uint16_t crc16_ccitt_sum(uint8_t *data, size_t length,uint16_t *crcSum) {
    uint16_t crc = *crcSum;     //0xFFFF;  // 鍒濆鍖朇RC瀵勫瓨鍣ㄤ负0xFFFF
    const uint16_t polynomial = 0x1021;  // CRC16-CCITT澶氶」寮忥紙鍙嶅皠鍚庯級

    for (size_t i = 0; i < length; i++) {
        crc ^= (data[i] << 8);  // 灏嗗綋鍓嶅瓧鑺傚乏绉�8浣嶅悗涓嶤RC瀵勫瓨鍣ㄨ繘琛屽紓鎴栬繍绠�
        for (uint8_t j = 0; j < 8; j++) {
            if (crc & 0x8000) {  // 妫�鏌ユ渶楂樹綅鏄惁涓�1
                crc = (crc << 1) ^ polynomial;  // 宸︾Щ骞跺紓鎴栧椤瑰紡
            } else {
                crc <<= 1;  // 浠呭乏绉�
            }
        }

        crc &= 0xFFFF;  // 纭繚CRC鍊煎湪16浣嶈寖鍥村唴锛堝疄闄呬笂杩欎竴姝ュ湪澶у鏁版儏鍐典笅鏄浣欑殑锛屽洜涓篊璇█涓殑浣嶈繍绠椾細鑷姩澶勭悊婧㈠嚭锛�
    }
    *crcSum=crc;
    return crc;
}
static inline uint16_t crc16_ccitt(uint8_t *data, size_t length) {
    uint16_t crc = 0xFFFF;  // 鍒濆鍖朇RC瀵勫瓨鍣ㄤ负0xFFFF
    const uint16_t polynomial = 0x1021;  // CRC16-CCITT澶氶」寮忥紙鍙嶅皠鍚庯級

    for (size_t i = 0; i < length; i++) {
        crc ^= (data[i] << 8);  // 灏嗗綋鍓嶅瓧鑺傚乏绉�8浣嶅悗涓嶤RC瀵勫瓨鍣ㄨ繘琛屽紓鎴栬繍绠�
        for (uint8_t j = 0; j < 8; j++) {
            if (crc & 0x8000) {  // 妫�鏌ユ渶楂樹綅鏄惁涓�1
                crc = (crc << 1) ^ polynomial;  // 宸︾Щ骞跺紓鎴栧椤瑰紡
            } else {
                crc <<= 1;  // 浠呭乏绉�
            }
        }

        crc &= 0xFFFF;  // 纭繚CRC鍊煎湪16浣嶈寖鍥村唴锛堝疄闄呬笂杩欎竴姝ュ湪澶у鏁版儏鍐典笅鏄浣欑殑锛屽洜涓篊璇█涓殑浣嶈繍绠椾細鑷姩澶勭悊婧㈠嚭锛�
    }

    return crc;
}

#endif // VPDCHECKMESSAGE_H
